package at.fhj.itm09.snake.activities;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import at.fhj.itm09.snake.R;
import at.fhj.itm09.snake.views.Preview;

/**
 * 
 * @author Susanne Brandstätter - Susanne.Brandstaetter.ITM09@fh-joanneum.at
 * @author Katharina Biela - Katharina.Biela.ITM09@fh-joanneum.at
 *
 * This activity gets called by clicking on the button in the settings activity.
 * 
 * By opening this activity, it will automatically starts the camera. By clicking
 * on the button the picture will be taken and stored on the mobilephone. 
 * During this process and also afterwards you can see the preview of your
 * photo on the display.
 * If you want to go back to the settings menu, you have to press the back button
 * on your phone. 
 * 
 */

public class CameraActivity extends Activity implements OnClickListener{
	private Preview preview;
	private Button buttonClick;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.camera_layout);

		preview = new Preview(this);
		
		try {
			((FrameLayout) findViewById(R.id.preview)).addView(preview);
			
		} catch (Exception e) {
			Log.e("Camera Error", "following error: " + e);
		}
				
		buttonClick = (Button) findViewById(R.id.buttonClick);
		buttonClick.setOnClickListener(this);
	}

	/**
	 * After clicking on the button, it will call the class preview, to
	 * show the taken picture on the display.
	 */
	public void onClick(View v) {
		preview.camera.takePicture(null, rawCallback, jpgCallback);
		
	}
	
	/** 
	 * Handles data for raw picture 
	 * It will be only used to call the method takePicture
	 */
	PictureCallback rawCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
		}
	};

	/** 
	 * Handles data for jpeg picture 
	 * It tries to save the picture on the following hardcoded path:
	 * 		/sdcard/mySnakePhoto.jpg
	 */
	PictureCallback jpgCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
			FileOutputStream outStream = null;
			try {
				// Writes the photo to the sdcard
				outStream = new FileOutputStream(String.format("/sdcard/mySnakePhoto.jpg", System.currentTimeMillis()));	
				outStream.write(data);
				outStream.close();

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
			}
		}
	};

}
